package com.sanmina.route.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sanmina.route.dao.RouteDao;
import com.sanmina.route.dao.RouteDaoImpl;
import com.sanmina.route.entity.Location;
import com.sanmina.route.entity.Route;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@WebServlet("/searchLocation")
public class SearchLocationAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// int start = Integer.valueOf(req.getParameter("start"));
		// int limit = Integer.valueOf(req.getParameter("limit"));
		// int page = Integer.valueOf(req.getParameter("page"));
		String workstation = "";
		workstation = req.getParameter("name");

		// int end = 0;
		RouteDao dao = new RouteDaoImpl();
		List<Location> locations = new ArrayList<Location>();
		List<Route> routes = new ArrayList<Route>();
		locations = dao.listAllLocations();
		routes = dao.listAllRoute();
		// if(workstation!="mercy"&&workstation!=null){
		// locations = dao.searchLoactionByName(workstation);
		// }else {
		// locations =dao.listAllLocations();
		// }

		// if(page!=1){
		// if(start>locations.size()){
		// start= 0;
		// }
		// }
		// List<Location> subLocations = new ArrayList<Location>();
		//
		// if (limit > 20)
		// limit = 20;
		// if ((locations.size() - start) < limit || limit == 0) {
		// end = locations.size();
		// } else {
		// end = start + limit;
		// }
		// subLocations = locations.subList(start, end);
		JSONArray ja;
		JSONObject jo = new JSONObject();
		ja = JSONArray.fromObject(locations);
		jo.put("locations", ja);
		ja = JSONArray.fromObject(routes);
		jo.put("routes", ja);
		// jo.put("locationCount", locations.size());
		// StringBuilder jsonBuilder = new StringBuilder("{'locations':[");
		// for (int i = 0; i < locations.size(); i++) {
		// Location location = locations.get(i);
		// jsonBuilder.append("{name:'").append(location.getWorkstation()).append("',");
		//
		// jsonBuilder.append("id:").append(location.getLocationKey()).append("}");
		// jsonBuilder.append(((i+1)==locations.size())?"":",");
		// }
		// jsonBuilder.append("]}}");
		// JSONObject object =JSONObject.fromObject(jsonBuilder.toString());
		resp.setCharacterEncoding("UTF-8");
		resp.setHeader("Cache-Control", "no-cache");
		resp.setContentType("text/html;charset=UTF-8");
		resp.getWriter().print(jo);
		resp.getWriter().close();

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doGet(req, resp);
	}
}
